/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package POSTApp;
import Payment.Payment;
import Store.Store;
import Product.ProductCatalog;
import Transaction.Transaction;
import Transaction.TransactionHeader;
import Transaction.TransactionItem;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller for the POST GUI.
 * @author Rebecca Bettencourt
 */
public class POSTController {
    private Store store;
    private ProductCatalog catalog;
    private List<Transaction> txQueue;

    public POSTController(Store store, ProductCatalog catalog) {
        this.store = store;
        this.catalog = catalog;
        this.txQueue = new ArrayList<Transaction>();
    }

    public void addProduct(ProductPanel pp, InvoicePanel ip) {
        try {
            int upc = pp.getUPC();
            int qty = pp.getQuantity();
            Product.Product p = catalog.lookupItem(upc);
            if (p == null) {
                javax.swing.JOptionPane.showMessageDialog(null, "This product could not be found.");
                return;
            }
            ip.addItem(p, qty);
            pp.clear();
        } catch (NumberFormatException nfe) {
            javax.swing.JOptionPane.showMessageDialog(null, "Please enter an integer for UPC and quantity.");
            return;
        }
    }

    public void checkOut(HeaderPanel hp, InvoicePanel ip, ProductPanel prp, PaymentPanel pp) {
        String cname = hp.getCustomerName();
        List<TransactionItem> items = ip.getItems();
        float total = 0;
        for (TransactionItem item : items) {
            Product.Product p = catalog.lookupItem(item.getUPC());
            total += p.getPrice() * item.getQuantity();
        }
        Payment p = pp.getPayment(total);
        if (p == null) {
            javax.swing.JOptionPane.showMessageDialog(null, "Please select a method of payment.");
            return;
        }
        if (!p.verify()) {
            javax.swing.JOptionPane.showMessageDialog(null, "This method of payment was rejected.");
            return;
        }
        if (p.getChange() > 0) {
            javax.swing.JOptionPane.showMessageDialog(null, "Give "+p.getChange()+" in change.");
        }
        TransactionHeader th = new TransactionHeader(cname);
        Transaction t = new Transaction(th, p);
        for (TransactionItem item : items) {
            t.addItem(item);
        }
        txQueue.add(t);
        javax.swing.JOptionPane.showMessageDialog(null, "Checkout complete.");
        hp.clearCustomerName();
        ip.clear();
        prp.clear();
        pp.clearPayment();

        try {
            while (!txQueue.isEmpty()) {
                store.recordSale(txQueue.get(0));
                txQueue.remove(0);
            }
        } catch (Exception e) {
            System.err.println("Could not contact store. Will try again after the next transaction.");
        }
    }
}
